package lol.clann.minecraft.springboot.plugin.core.config.jackson.fill;

import relocate.com.fasterxml.jackson.core.JsonParser;
import relocate.com.fasterxml.jackson.core.JsonProcessingException;
import relocate.com.fasterxml.jackson.databind.DeserializationContext;
import relocate.com.fasterxml.jackson.databind.JsonDeserializer;
import lol.clann.minecraft.springboot.plugin.core.config.jackson.Jackson;

import java.io.IOException;

/**
 * 实现反序列化和填充操作
 *
 * @author pyz
 * @date 2018/10/14 上午12:52
 */
public abstract class BaseJsonDeserializer<T> extends JsonDeserializer<T> {
    @Override
    public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        T value = (T) Jackson.getTarget(true);
        if (value == null) {
            return create(p, ctxt);
        } else {
            fill(value, p, ctxt);
            return value;
        }
    }

    /**
     * 反序列化(创建)
     *
     * @param p
     * @param context
     * @return
     * @throws IOException
     * @throws JsonProcessingException
     */
    protected abstract T create(JsonParser p, DeserializationContext context) throws IOException, JsonProcessingException;

    /**
     * 反序列化(填充)
     *
     * @param value
     * @param p
     * @param context
     * @return
     * @throws IOException
     * @throws JsonProcessingException
     */
    protected abstract T fill(T value, JsonParser p, DeserializationContext context) throws IOException, JsonProcessingException;
}
